<!DOCTYPE html>
<html>
<head>
    <title>贪吃蛇游戏</title>
    <style>
        canvas {
            background-color: #f0f0f0;
            display: block;
            margin: auto;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }
    </style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
    var canvas = document.getElementById('gameCanvas');
    var context = canvas.getContext('2d');
    var box = 20;
    var snake = [];
    snake[0] = {
        x: 9 * box,
        y: 10 * box
    };
    var food = {
        x: Math.floor(Math.random() * 19 + 1) * box,
        y: Math.floor(Math.random() * 19 + 1) * box
    };
    var score = 0;
    var d;

    document.addEventListener("keydown", direction);

    function direction(event) {
        var key = event.keyCode;
        switch (key) {
            case 37:
                if (d != "RIGHT") {
                    d = "LEFT";
                }
                break;
            case 38:
                if (d != "DOWN") {
                    d = "UP";
                }
                break;
            case 39:
                if (d != "LEFT") {
                    d = "RIGHT";
                }
                break;
            case 40:
                if (d != "UP") {
                    d = "DOWN";
                }
                break;
        }
    }

    function draw() {
        context.clearRect(0, 0, 400, 400);
        for (var i = 0; i < snake.length; i++) {
            context.fillStyle = (i === 0) ? "#4CAF50" : "white";
            context.fillRect(snake[i].x, snake[i].y, box, box);
        }

        context.fillStyle = "red";
        context.fillRect(food.x, food.y, box, box);

        var snakeX = snake[0].x;
        var snakeY = snake[0].y;

        if (d == "LEFT") snakeX -= box;
        if (d == "UP") snakeY -= box;
        if (d == "RIGHT") snakeX += box;
        if (d == "DOWN") snakeY += box;

        snake.unshift({ x: snakeX, y: snakeY });

        if (snakeX === food.x && snakeY === food.y) {
            score++;
            food = {
                x: Math.floor(Math.random() * 19 + 1) * box,
                y: Math.floor(Math.random() * 19 + 1) * box
            };
        } else {
            snake.pop();
        }

        for (var i = 4; i < snake.length; i++) {
            if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
                snake = [];
            }
        }

        setTimeout(draw, 100);
    }

    draw();
</script>
</body>
</html>